<template>
  <header>
      <!-- <x-header :left-options="{showBack: false}">区域监管</x-header> -->
    <x-header :left-options="{showBack: false}" v-if="allMap.info" class="infoSearch" >{{allMap.info}}</x-header>
    <div id="allmap" style="height: 100%;"></div>
  </header>
</template>

<script>
import axios from 'axios';
import {gcj02tobd09, wgs84togcj02} from '../assets/position';
// import { setTimeout } from 'timers';
export default {
  name: 'Header',
  data () {
    return {
      allMap: {
        map: null,
        info: ''
      },
      areaName: '',
      areaorg: '',
      LocalQuery: {
        lng: '',
        lat: ''
      },
      polygon: null,
      walking: null,
      driving: null,
      nextData: [],
      personIcon: '/static/人.png', 
      carIcon: '/static/车.png',
      id: '',
      lineData: [],
      allperson: [],
      allcar: [], 
      alldata: [],
      position: '/static/当前位置.png'
    }
  },
  created () {
    axios.get('/wxapp/getUrl/get_jsapi_ticket.jhtml', {
      params: {
        url: location.href.split('#')[0]
      }
    }).then((res) => {
      let datas = res.data.split('#');
      // datas.split('#'));
      // console.log(datas[1]);
      let result = /\w+$/.exec(datas[0]);
      let result2 = /\w+$/.exec(datas[1]);
      // console.log(datas[2]);
      let result3 = datas[2].substr(9)
      let result4 = +result2;    
      this.$wechat.config({
        beta: true,
        debug: false,
        appId: 'wx45ebbfbac8732e66',
        timestamp: result4,
        nonceStr: result3,
        signature: result[0],
        jsApiList: ['getLocation']
      });
      // alert('正在');
    })
  },
  mounted () {  
    // this.allMap.map = new BMap.Map('allmap');
    // var navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); 
    // this.allMap.map.addControl(navigation);
    // this.allMap.map.enableScrollWheelZoom(true);
    // var point = new BMap.Point(117.06533, 36.68013); // 创建点坐标
  // this.allMap.map.enableScrollWheelZoom(true);
    // this.allMap.map.centerAndZoom(point, 11); 
    // alert('dasd')
    this.$wechat.ready(() => {
      // alert('开始');
      this.$wechat.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: (res) => {
          // alert(res);
          // console.log(res);
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          // var speed = res.speed
          // var accuracy = res.accuracy;
          // console.log(accuracy, speed)
          // wgs84togcj02
          let wgs = wgs84togcj02(longitude, latitude);
          let gcj = gcj02tobd09(wgs[0], wgs[1]);
          let query = {
            lng: gcj[0],
            lat: gcj[1]
          }
          console.log(query);
          // console.log(this.LocalQuery)
          this.LocalQuery = query;
          window.sessionStorage.setItem('map', JSON.stringify(query));
          // if (query) {
          this.getmap();          
          // this.getAxios(query); 
          // this.getIcon();
          // }
          // this.getData()           
          // window.sessionStorage.setItem('map', JSON.stringify(query));
          // next();
        },
         cancel: function (res) {
          //  alert('')
      // getShopList();
    },
    complete: function (res) {
      // alert(res);
    },
    fail: function (res) {
      // getShopList();
      console.log('fail')
    }
      })
    });
  },
  methods: {
    getmap () {
      // console.log(query);
      this.allMap.map = new BMap.Map('allmap');
      var navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); 
      this.allMap.map.addControl(navigation);
      this.allMap.map.enableScrollWheelZoom(true);
      var point = new BMap.Point(this.LocalQuery.lng, this.LocalQuery.lat); // 创建点坐标
      // this.allMap.map.enableScrollWheelZoom(true);
      this.allMap.map.centerAndZoom(point, 11);
      // this.getmap(query);          
      this.getAxios(); 
      this.getIcon();
    },
    getIcon () {
      // console.log('aa')
      // console.log(this.LocalQuery);
      var pt = new BMap.Point(this.LocalQuery.lng, this.LocalQuery.lat);
      var myIcon = new BMap.Icon(this.position, new BMap.Size(40, 40));
      var marker2 = new BMap.Marker(pt, {icon:myIcon});  // 创建标注
      this.allMap.map.addOverlay(marker2);
      // marker2.disableMassClear();              
      // var point = new BMap.Point(this.LocalQuery.lng, this.LocalQuery.lat); // 创建点坐标      
    },
    getPerson (id) {
      id = String(id)
      axios.get('/dsp-personmonitor-ui/getPersonliableIndex', {
        params: { 
          id: id
        }
      }).then((res) => {
        // console.log(res);
          this.allperson = res.data.worker;
          this.allcar = res.data.car;  
          // this.allperson = []; 
          // console.log(this.allcar)       
        // console.log(this.allperson)
      });
    },
    //  getCar  (id) {
    //   id = String(id)
    //   axios.post('/api/wechat/getPerson', {
    //     id: id
    //     }).then((res) => {
    //       this.allperson = res.data.data;
    //       console.log(res);
    //     // console.log(this.allperson)
    //   });
    // },
    getAxios () {
      // console.log(this.LocalQuery);
      axios.get('/dsp-personmonitor-ui/getPersonliable', {
        params: {
          lat: this.LocalQuery.lat,
          lng: this.LocalQuery.lng
        }
      }).then((res) => {
        // console.log(res);
        let data = res.data;
        let arrSplit, id;        
        arrSplit = data.dutyarea.split('P');
        this.areaName = res.data.name;
        this.areaorg = res.data.orgname;        
        id = data.id;
        window.localStorage.setItem('id', data.orgid);                  
        let Arr = arrSplit.pop(); 
        // console.log(arrSplit)     
        // console.log(data)
        // let arrSplit, id;
        // for (let i = 0; i < data.length; i++) {
        //   arrSplit = data[i].split('P');
        //   // console.log(arrSplit);
        //   id = data[i].id;
        //   window.localStorage.setItem('id', data[i].orgid);
        //   let Arr = arrSplit.pop();
        // }
        // console.log(arrSplit)
        for (let i = 0, len = arrSplit.length; i < len; i++) {
          // console.log(arrSplit[i].split('_')[1])
          let wgs = wgs84togcj02(arrSplit[i].split('_')[1], arrSplit[i].split('_')[0]);  
          // console.log(wgs)        
          let gcj = gcj02tobd09(wgs[0], wgs[1]);
          // console.log(gcj);
          // console.log(gcj)
          this.alldata.push({lng: gcj[0], lat: gcj[1]});            
        } 
        // console.log(this.alldata)
        // console.log(this.alldata);
        // setTimeout(() => {
        //   this.getData()  
        // }, 500);
        // console.log('aaaaaaa');
        this.getPerson(id);
        // this.getCarData(id)
        // console.log(this.allcar);            
        setTimeout(() => {
          this.getData()          
        }, 200);
        // this.getData()
      });
    },
    getData () {
      let ppp = [];
      // console.log(this.allperson);
      // console.log(this.alldata);      
        // var pt = new BMap.Point(this.query.lng, this.query.lat);
      // var myIcon = new BMap.Icon("http://lbsyun.baidu.com/jsdemo/img/fox.gif", new BMap.Size(300,157));
      // var marker2 = new BMap.Marker(pt, {icon:myIcon});  // 创建标注
      for (let index = 0; index < this.alldata.length; index++) {
        const element = this.alldata[index];
        // console.log(element);
        ppp.push(new BMap.Point(element.lng, element.lat)); 
        // console.log(ppp)            
      }
      this.polygon = new BMap.Polygon(ppp, {strokeColor: "green", strokeWeight: 2, strokeOpacity: 0.5, fillColor: 'green', enableClicking: true});
          let works = '';
          let workname = '';
          if (this.allperson.length === 0) {
            works = '';
            workname = '';
          } else {
            works = this.allperson[0].workerId;
            workname = this.allperson[0].workers;
            // console.log(workname);
          }
      var content =
        `<div id="windowinfo">
          <div class="commons"><span>区域名称 : </span><span>${this.areaName}</span></div>
          <div class="commons"><span>所属项目部 : </span><span id="plate">${this.areaorg}</span></div>
          <div style="display: none;" id="infonumber1">${this.allcar[0].carId}</div>
          <div>
          <div style="display: none;" id="name0">${works}</div>
          </div>
          <div class="commons"><span>收运车辆: </span><span><a style="text-decoration: underline; color: blue" id="infonumber">${this.allcar[0].carnum}</a></span></div>                                                 
          <div ${workname === '' ? 'class="hidden"' : 'class = "commons"'}><span>保洁人员: </span><span><a style="text-decoration: underline; color: blue" id="infoname0">${workname}</a></span>
          </div>
        </div>`;
      // console.log('111');
      let that = this;
      let len = this.polygon.getPath();
      this.allMap.map.addEventListener('touchend', function(e){
        let MaxArray = [];
        let MinArray = [];
        for (let i = 0; i < len.length; i++) {
          MaxArray.push(len[i].lng);
          MinArray.push(len[i].lat);
        }
        const MaxNum = Math.max.apply(null, MaxArray);
        const MinNum = Math.min.apply(null, MaxArray);
        const MaxNum1 = Math.max.apply(null, MinArray);
        const MinNum1 = Math.min.apply(null, MinArray);
        if ((MaxNum > e.point.lng && e.point.lng > MinNum) && (MaxNum1 > e.point.lat && e.point.lat > MinNum1)) {
            if (MaxNum - e.point.lng) that.openInfo(content, e);            
        }
      });
      this.polygon.disableMassClear();
      // console.log(polygon);  
      this.allMap.map.addOverlay(this.polygon);
      // this.allMap.map.addOverlay(marker2);      
    },
    // getCarData (id) {
    //   id = String(id)
    //   axios.post('/api2/wechat/getCarInfo', {
    //     id: id
    //     }).then((res) => {
    //       this.allcar = res.data.data;
    //     // console.log(this.allperson)
    //   });
    // },
    addClickHandlers (content, polygon) {
      const that = this;
      // console.log('111')
      polygon.addEventListener("click", function (e) {
        // console.log('111')
        that.openInfo(content, e);
      });
      polygon.disableMassClear();      
    },
    openInfo (content, e) {
      let p = e.point;
      // console.log(e);
      let point = new BMap.Point(p.lng, p.lat); //  窗口经纬度
      // let point = new BMap.Point(p[0].lng, p[0].lat); //  窗口经纬度
      let infoWindow = new BMap.InfoWindow(content); //  创建信息窗口对象
      let that = this;
      EventWrapper.addListener(infoWindow, 'open', function (e) {
        let infonumber = document.getElementById('infonumber');
        let infonumber1 = document.getElementById('infonumber1').innerHTML;        
        let infoname0 = document.getElementById('infoname0');
        // // let infoname1 = document.getElementById('infoname1');
        // // let infoname2 = document.getElementById('infoname2');
        let nameId0 = document.getElementById('name0').innerHTML;
        // // console.log(nameId0);
        // // let nameId1 = document.getElementById('name1').innerHTML;
        // // let nameId2 = document.getElementById('name2').innerHTML;
        infonumber.addEventListener('click', function (e) {
          // console.log('王大特');
          that.getcar(infonumber1);
        });
        infoname0.addEventListener('click', function (e) {
          // let nameId0.inn
          // that.personPush();
          that.getperson(nameId0);
        });
        // infoname1.addEventListener('click', function (e) {
        //   // that.personPush();
        //   that.getperson(nameId1);          
        // });
        // infoname2.addEventListener('click', function (e) {
        //   // that.personPush();
        //   that.getperson(nameId2);          
        // });
      });
      that.allMap.map.openInfoWindow(infoWindow, point); // 开启信息窗口
    },
    getcar (name) {
      // console.log(name);
      let firstElemen = this.allcar.find((element, index, array) => {
        // console.log(currentValue)
        return name === element.carId ? element : '';
      });
      // console.log(firstElemen);
      this.getData2(firstElemen, 'car');
      // console.log('我去你的吧')
      this.getpp(firstElemen, 'car')      
    },
    getData2 (data) {
      // console.log(this.driving);
      if (this.walking) {
        console.log('大苏打');
        // this.walking.clearResults();
        this.walking.clearResults();
        this.getData();                
      }
      if (this.driving !== null) {
        // this.walking.hide();
        // this.allMap.map.removeOverlay(this.walking);
        this.driving.clearResults();
        // console.log(this.allMap.map)
        // this.allMap.map.clearOverlays();
        this.getData();
      }
      // console.log(data);
      let gcj = gcj02tobd09(data.carX, data.carY);
      var output = "距离: ";
      console.log(output)
      this.driving = new BMap.DrivingRoute(this.allMap.map, {renderOptions: {map: this.allMap.map},
        onSearchComplete: (results) => {
          if (this.driving.getStatus() !== BMAP_STATUS_SUCCESS) {
            return false;
          }
          // console.log(results)
          var plan = results.getPlan(0);
          output += plan.getDistance(true) + "\n";
        },
        onPolylinesSet: () => {
          // console.log(output)
          this.allMap.info = output;
        },
        onMarkersSet: (pois) => {
          this.allMap.map.removeOverlay(pois[0].marker); //删除起点
          this.allMap.map.removeOverlay(pois[1].marker); //删除起点          
        }
      });
      // console.log(this.LocalQuery)
      var start = new BMap.Point(this.LocalQuery.lng, this.LocalQuery.lat);
      var end = new BMap.Point(gcj[0], gcj[1]);
      this.driving.search(start, end); 
    },
    getperson (id) {
      // console.log(id)
      let datas = this.allperson;
      // console.log(this.allperson)
      let IndexData;
      for (const key in datas) {
        if (datas.hasOwnProperty(key)) {
          const element = datas[key];
          // console.log(id == element.workerId)
          if (id == element.workerId) {
            IndexData = element;
            break;
          }
        }
      }
      this.getData1(IndexData)
      this.getpp(IndexData, 'person')
    },
    getpp (data, name) {      
      let myIcon;
      let gcj;
      let names;
      // console.log(data);
      if (name === 'person') {
        gcj = gcj02tobd09(data.workerX, data.workerY);                
        myIcon = new BMap.Icon(this.personIcon, new BMap.Size(30,40));
        names = data.workers;
      } else {
        gcj = gcj02tobd09(data.carX, data.carY);        
        myIcon = new BMap.Icon(this.carIcon, new BMap.Size(30,40));
        names = data.carnum;        
      }
      // this.allMap.map.clearOverlays();
      // let gcj = gcj02tobd09(data.carX, data.carY);
      if (this.nextData.length !== 0) {
        for (let index = 0; index < this.nextData.length; index++) {
          const element = this.nextData[index];
          element.hide();
          // this.allMap.map.clearOverlays();          
        }
      } 
      var pt = new BMap.Point(gcj[0], gcj[1]);
      var marker2 = new BMap.Marker(pt, {icon: myIcon});  // 创建标注
      this.allMap.map.addOverlay(marker2);              // 将标注添加到地图中
      var label = new BMap.Label(names, {offset:new BMap.Size(0,40)});
      label.setStyle({
        border: '1px solid',
        color: '#000'
      })
      marker2.setLabel(label);
      this.nextData.push(marker2)
    },
    getData1 (data) {
      // console.log(this.walking);
      if (this.driving) {
        // this.walking.clearResults();
        this.driving.clearResults();  
        this.getData();                              
      }
      // console.log(data);
      if (this.walking !== null) {
        // this.walking.hide();
        // this.allMap.map.removeOverlay(this.walking);
        this.walking.clearResults();
        // console.log(this.allMap.map)
        // this.allMap.map.clearOverlays();
        this.getData();
      }
      let gcj = gcj02tobd09(data.workerX, data.workerX);
      var output = "距离: ";
      this.walking = new BMap.WalkingRoute(this.allMap.map, {renderOptions: {map: this.allMap.map},
        onSearchComplete: (results) => {
          if (this.walking.getStatus() !== BMAP_STATUS_SUCCESS) {
            return false;
          }
          var plan = results.getPlan(0);
          output += plan.getDistance(true) + "\n";
        },
        onPolylinesSet: () => {
          this.allMap.info = output;
        },
        onMarkersSet: (pois) => {
          this.allMap.map.removeOverlay(pois[0].marker); //删除起点
          this.allMap.map.removeOverlay(pois[1].marker); //删除起点          
        }
      });
      var start = new BMap.Point(this.LocalQuery.lng, this.LocalQuery.lat);
      var end = new BMap.Point(gcj[0], gcj[1]);
      this.walking.search(start, end); 
    }
  }
}
</script>
<style lang="less">
// @header-background-color: #08b2ff;
  header {
    height: 100%;
    position: relative;
    bottom: 50px;
    .vux-header {
      // background: @header-background-color;
      position: fixed;
      width: 100%;
      z-index: 1;
      // height: 60px;
      // line-height: 60px;
      .vux-header-title {
        line-height: 40px;        
      }
      // padding: 0;
    }
  }
  .infoSearch {
    position: fixed;
    text-align: center;
    top: 0px;
    z-index: 2;
    background: #9e9e9e;
    opacity: .6;
    width: 100%;
    color:#fff;
  }
  .commons {
    padding: 6px;
    // font-size: 14px;
  }
  .hidden {
    display: none;
  }
</style>
